package com.hwhhhh.mygrad;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.DialogFragment;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;

import com.hwhhhh.mygrad.dto.UserDTO;
import com.hwhhhh.mygrad.fragment.CommentFragment;
import com.hwhhhh.mygrad.fragment.HintDialogFragment;
import com.hwhhhh.mygrad.utils.StringUtils;

import java.io.Serializable;

public abstract class BaseActivity extends AppCompatActivity{
    private static final int CAMERA_PERMISSION_CODE = 100;
    private static final int STORAGE_PERMISSION_CODE = 101;

    public Context mContext;
    private Toast mToast;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
        setContentView(initLayout());
        initView();
        initData();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    protected abstract void initView();

    protected abstract int initLayout();

    protected abstract void initData();

    /**
     * 显示toast提示
     * @param msg 提示信息
     */
    public void showToast(String msg) {
        if (mToast == null) {
            mToast = Toast.makeText(mContext, msg, Toast.LENGTH_SHORT);
        } else {
            mToast.setText(msg);
            mToast.setDuration(Toast.LENGTH_SHORT);
        }
        mToast.show();
    }

    public void showToastSync(String msg) {
        Looper.prepare();
        if (mToast == null) {
            mToast = Toast.makeText(mContext, msg, Toast.LENGTH_SHORT);
        } else {
            mToast.setText(msg);
            mToast.setDuration(Toast.LENGTH_SHORT);
        }
        mToast.show();
        Looper.loop();
    }

    /**
     * activity的跳转
     * @param cls 跳转的类
     */
    public void navigateTo(Class cls) {
        Intent in = new Intent(mContext, cls);
        startActivity(in);
    }

    public void navigateToWithBundle(Class cls, Bundle bundle) {
        Intent in = new Intent(mContext, cls);
        in.putExtras(bundle);
        startActivity(in);
    }

    public void navigateToWithFlag(Class cls, int flags) {
        Intent in = new Intent(mContext, cls);
        in.setFlags(flags);
        startActivity(in);
    }

    public void navigateToWithBundle(Class cls, int flags, Bundle bundle) {
        Intent in = new Intent(mContext, cls);
        in.putExtras(bundle);
        in.setFlags(flags);
        startActivity(in);
    }

    public void navigateTo(Class cls, String key, String val) {
        Intent in = new Intent(mContext, cls);
        in.putExtra(key, val);
        startActivity(in);
    }

    public void navigateTo(Class cls, String key, Serializable val) {
        Intent in = new Intent(mContext, cls);
        in.putExtra(key, val);
        startActivity(in);
    }

    public void saveStringToSp(String key, String val) {
        SharedPreferences sp = getSharedPreferences("sp_bisturoom", MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.putString(key, val);
        editor.apply();
    }


    public String getStringFromSp(String key) {
        SharedPreferences sp = getSharedPreferences("sp_bisturoom", MODE_PRIVATE);
        return sp.getString(key, "");
    }

    public void setBarColor(int color) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
            this.getWindow().setStatusBarColor(ContextCompat.getColor(this, color));
        }
    }

    public CommentFragment showCommentFragment(int clsId, int parentId, String text){
        CommentFragment commentFragment = CommentFragment.getNewInstance(clsId, parentId, text);
        commentFragment.setStyle(DialogFragment.STYLE_NORMAL, R.style.dialogFullScreen);
        commentFragment.show(getSupportFragmentManager(), CommentFragment.class.getSimpleName());
        return commentFragment;
    }

    public void checkCameraPermission() {
        // 检查是否有相机权限
        // 检查权限的方法: ContextCompat.checkSelfPermission()两个参数分别是Context和权限名.
        // 返回PERMISSION_GRANTED是有权限，PERMISSION_DENIED没有权限
        if (ContextCompat.checkSelfPermission(BaseActivity.this,
                Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED) {
            //没有权限，向系统申请该权限。
            Log.i("MY","没有权限");
            requestPermission(CAMERA_PERMISSION_CODE);
        }
//        else {
//            //同组的权限，只要有一个已经授权，则系统会自动授权同一组的所有权限，比如WRITE_EXTERNAL_STORAGE和READ_EXTERNAL_STORAGE
//            Toast.makeText(BaseActivity.this, "已获取相机权限",Toast.LENGTH_SHORT).show();
//        }
    }

    public void checkStoragePermission() {
        // 检查是否有存储的读写权限
        // 检查权限的方法: ContextCompat.checkSelfPermission()两个参数分别是Context和权限名.
        // 返回PERMISSION_GRANTED是有权限，PERMISSION_DENIED没有权限
        if (ContextCompat.checkSelfPermission(BaseActivity.this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            //没有权限，向系统申请该权限。
            Log.i("MY","没有权限");
            requestPermission(STORAGE_PERMISSION_CODE);
        }
//        else {
//            //同组的权限，只要有一个已经授权，则系统会自动授权同一组的所有权限，比如WRITE_EXTERNAL_STORAGE和READ_EXTERNAL_STORAGE
//            Toast.makeText(BaseActivity.this, "已获取存储的读写权限",Toast.LENGTH_SHORT).show();
//        }
    }

    private void requestPermission(int permissionCode) {
        String permission = getPermissionString(permissionCode);
        if (!StringUtils.isEmpty(permission)){
            // Should we show an explanation?
            if (ActivityCompat.shouldShowRequestPermissionRationale(BaseActivity.this,
                    permission)) {
                // Show an expanation to the user *asynchronously* -- don't block
                // this thread waiting for the user's response! After the user
                // sees the explanation, try again to request the permission.
                if(permissionCode == CAMERA_PERMISSION_CODE) {
                    DialogFragment newFragment = HintDialogFragment.newInstance(R.string.camera_description_title,
                            R.string.camera_description_why_we_need_the_permission,
                            permissionCode);
                    newFragment.show(getSupportFragmentManager(), HintDialogFragment.class.getSimpleName());
                } else if (permissionCode == STORAGE_PERMISSION_CODE) {
                    DialogFragment newFragment = HintDialogFragment.newInstance(R.string.storage_description_title,
                            R.string.storage_description_why_we_need_the_permission,
                            permissionCode);
                    newFragment.show(getSupportFragmentManager(), HintDialogFragment.class.getSimpleName());
                }


            } else {
                Log.i("MY","返回false 不需要解释为啥要权限，可能是第一次请求，也可能是勾选了不再询问");
                ActivityCompat.requestPermissions(BaseActivity.this,
                        new String[]{permission}, permissionCode);
            }
        }
    }

    public String getPermissionString(int requestCode){
        String permission = "";
        switch (requestCode){
            case CAMERA_PERMISSION_CODE:
                permission = Manifest.permission.CAMERA;
                break;
            case STORAGE_PERMISSION_CODE:
                permission = Manifest.permission.WRITE_EXTERNAL_STORAGE;
                break;
        }
        return permission;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {
        switch (requestCode) {
            case CAMERA_PERMISSION_CODE: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//                    Toast.makeText(BaseActivity.this,"相机权限已获取",Toast.LENGTH_SHORT).show();
                    Log.i("MY","相机权限已获取");
//                    startLocation();
                } else {
                    Toast.makeText(BaseActivity.this,"相机权限被拒绝",Toast.LENGTH_SHORT).show();
                    Log.i("MY","相机权限被拒绝");
                    if(!ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)){
                        DialogFragment newFragment = HintDialogFragment.newInstance(R.string.camera_description_title,
                                R.string.camera_description_why_we_need_the_permission,
                                requestCode);
                        newFragment.show(getSupportFragmentManager(), HintDialogFragment.class.getSimpleName());
                        Log.i("MY","false 勾选了不再询问，并引导用户去设置中手动设置");
                        return;
                    }
                }
                return;
            }
            case STORAGE_PERMISSION_CODE: {
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//                    Toast.makeText(BaseActivity.this,"存储权限已获取",Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(BaseActivity.this,"存储权限被拒绝",Toast.LENGTH_SHORT).show();
                    Log.i("MY","定位权限被拒绝");
                    if(!ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                        DialogFragment newFragment = HintDialogFragment.newInstance(R.string.storage_description_title,
                                R.string.storage_description_why_we_need_the_permission,
                                requestCode);
                        newFragment.show(getSupportFragmentManager(), HintDialogFragment.class.getSimpleName());
                        Log.i("MY","false 勾选了不再询问，并引导用户去设置中手动设置");
                    }
                    return;
                }
            }
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    public UserDTO getUser() {
        return StringUtils.fromJson(getStringFromSp("user"), UserDTO.class);
    }

}